/**
 * Tauri API 安全调用工具
 * 处理非Tauri环境的调用，提供模拟数据
 */

// 安全的invoke函数，处理非Tauri环境
export const safeInvoke = async <T = any>(command: string, args?: any): Promise<T> => {
  try {
    // 检查是否在Tauri环境中
    if (typeof window !== 'undefined' && (window as any).__TAURI__) {
      const { invoke } = await import('@tauri-apps/api/core');
      return await invoke(command, args);
    } else {
      // 在非Tauri环境中返回模拟数据
      console.warn('Running in non-Tauri environment, using mock data');
      return getMockData(command, args) as T;
    }
  } catch (error) {
    console.error('Failed to invoke Tauri command:', error);
    return getMockData(command, args) as T;
  }
};

// 模拟设置数据 - 移到函数外部以保持状态
const mockSettings: Record<string, string> = {
  'show_back_button': 'true',
  'enable_countdown': 'true',
  'countdown_duration': '30',
  'enable_sound': 'true',
  'enable_music': 'true',
  'auto_update': 'false',
  'server_url': 'https://tv-games-api.example.com',
  'enable_escape_key': 'true',
  'enable_context_menu': 'true',
  'enable_keyboard_navigation': 'true'
};

// 模拟数据函数 - 用于非Tauri环境测试
const getMockData = (command: string, args?: any): any => {
  
  switch (command) {
    case 'get_setting':
      const key = args?.key || '';
      return Promise.resolve({ value: mockSettings[key] || '' });
      
    case 'update_setting':
      const updateKey = args?.request?.key || '';
      const updateValue = args?.request?.value || '';
      if (updateKey) {
        mockSettings[updateKey] = updateValue;
      }
      return Promise.resolve();
      
    case 'get_settings':
      return Promise.resolve(
        Object.entries(mockSettings).map(([key, value]) => ({ key, value }))
      );
      
    case 'reset_settings':
      // 重置所有设置为默认值
      Object.assign(mockSettings, {
        'show_back_button': 'true',
        'enable_countdown': 'true',
        'countdown_duration': '30',
        'enable_sound': 'true',
        'enable_music': 'true',
        'auto_update': 'false',
        'server_url': 'https://tv-games-api.example.com',
        'enable_escape_key': 'true',
        'enable_context_menu': 'true',
        'enable_keyboard_navigation': 'true'
      });
      return Promise.resolve();
      
    default:
      return Promise.resolve([]);
  }
};